package com.wujunshen.snowflake.web.controller;

import com.wujunshen.snowflake.bean.ID;
import com.wujunshen.snowflake.bean.MakeID;
import com.wujunshen.snowflake.service.IdService;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author frank woo(吴峻申) <br>
 * email:<a href="mailto:frank_wjs@hotmail.com">frank_wjs@hotmail.com</a> <br>
 * @date 2020/2/7 5:33 下午 <br>
 */
@Slf4j
@RestController
public class IdController {
    @Resource
    private IdService idService;
    
    @GetMapping(value = "/id")
    public long genId() {
        return idService.genId();
    }
    
    @GetMapping("/id/{id:[0-9]*}")
    public ID explainId(@PathVariable("id") long id) {
        log.info("id is {}", id);
        return idService.expId(id);
    }
    
    @GetMapping("/time/{time:[0-9]*}")
    public String transTime(@PathVariable("time") long time) {
        log.info("time is {}", time);
        return DateFormatUtils.format(idService.transTime(time), "yyyy-MM-dd HH:mm:ss");
    }
    
    @PostMapping("/id")
    public long makeId(@RequestBody MakeID makeId) {
        long worker = makeId.getMachine();
        long time = makeId.getTime();
        long sequence = makeId.getSeq();
        log.info("worker is {}", worker);
        log.info("time is {}", time);
        log.info("sequence is {}", sequence);
        
        if (time == -1 || sequence == -1) {
            throw new IllegalArgumentException("Both time and sequence are required.");
        }
        
        return worker == -1
                ? idService.makeId(time, sequence)
                : idService.makeId(time, worker, sequence);
    }
}
